package com.mall.b2c.hessian.impl;

import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.google.common.collect.Lists;
import com.mall.b2c.bean.BrandBean;
import com.mall.b2c.bean.TagBean;
import com.mall.b2c.domain.goods.BrandDomain;
import com.mall.b2c.domain.goods.TagDomain;
import com.mall.b2c.hessian.GoodsExtendHessian;
import com.mall.b2c.service.BrandService;
import com.mall.b2c.service.GoodsService;
import com.mall.b2c.service.TagService;
import com.mall.common.bean.Order;
import com.mall.common.bean.Order.Direction;
import com.mall.common.bean.Pager;
import com.mall.common.exception.NoticeException;
import com.mall.common.hessian.impl.BaseHessianImpl;
import com.mall.common.hibernate.Finder;

@Service("b2cGoodsExtendHessian")
public class GoodsExtendHessianImpl extends BaseHessianImpl implements GoodsExtendHessian{

	@Resource private TagService tagService;
	@Resource private BrandService brandService;
	@Resource private GoodsService goodsService;
	
	@Override
	public String getTagList(Long[] tagIds) {
		List<TagDomain> tags = tagService.find(tagIds);
		if(!CollectionUtils.isEmpty(tags)){
			List<TagBean> beans = Lists.newLinkedList();
			for(TagDomain tag : tags){
				beans.add(new TagBean(tag));
			}
			return listToJson(beans);
		}
		return null;
	}

	@Override
	public String getBrandPagerData(Integer page, Integer size) {
		Pager pager = newPager(page, size);
		Finder finder = Finder.create("select new com.mall.b2c.bean.BrandBean(bean) from BrandDomain bean order by bean.priority");
		return objToJson(brandService.findByPagerForHessian(pager, finder));
	}

	@Override
	public String getBrandGoodsPager(Long brandId, Integer page, Integer size) {
		JSONObject result = new JSONObject();
		BrandDomain brand = brandService.find(brandId);
		if(brand == null){
			throw new NoticeException("该品牌不存在");
		}
		result.put("brand", new BrandBean(brand));
		Finder finder = Finder.create("select new com.mall.b2c.bean.GoodsBean(bean) from GoodsDomain bean where bean.brand.id = :brandId and bean.isMarketable=true");
		finder.setParam("brandId", brandId);
		Pager pager = new Pager();
		if(page != null){
			pager.setPageNumber(page);
		}
		pager.setPageSize(size);
		result.put("pager", goodsService.findByPagerForHessian(pager, finder));
		return objToJson(result);
	}

	@Override
	public String getBrandList(String firstCharacter, Boolean isRecommend,
			Integer count, String goodsCategoryCode, String order) {
		List<Order> orders = Lists.newLinkedList();
		if(StringUtils.isNotBlank(order)){
			String[] orderBy = order.split(" ");
			orders.add(new Order(orderBy[0],Direction.valueOf(orderBy[1])));
		}
		return listToJson(brandService.getBrandList(isRecommend, count, firstCharacter, goodsCategoryCode, orders));
	}

}
